package user.models;

import helpers.GeneralHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import entities.Category;

public class CategoryModel {
	
	private Objectify ofy;

	private Cache cache = null;

	private String cachePrefix = "category_";

	private static CategoryModel instance = null;
	
	public static CategoryModel getInstance() {
		if (instance == null) {
			instance = new CategoryModel();
		}
		
		return instance;
	}
	
	private CategoryModel() {
		try {
			ObjectifyService.register(Category.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public List<Category> listWithLevel(int level) {
		List<Category> categories = new ArrayList<Category>();
		
		categories = ofy.query(Category.class).filter("level <=", level).list();
		
		if (categories == null) {
			categories = new ArrayList<Category>();
		}
		
		//Sort category
		Collections.sort(categories, new Comparator<Category>(){
            public int compare(Category o1, Category o2) {
            	Category c1 = (Category) o1;
            	Category c2 = (Category) o2;
               return c1.getParents().compareToIgnoreCase(c2.getParents());
            }
        });
		
		return categories;
	}
	
	public Category getCategory(String id) {
		
		Category category = new Category();
		
		try {
			category = ofy.get(new Key<Category>(Category.class, id));
		} catch (Exception e) {
			category = null;
		}
		
		return category;
	}
	
	public void update(Category category) {
		ofy.put(category);
	}
	
	public Map<String, Category> getByListId(List<String> ids) {
		Map<String, Category> categories = new TreeMap<String, Category>();
		
		try {
			categories = ofy.get(Category.class, ids);
		} catch (Exception e) {
			
		}
		
		return categories;
	}
	
	public List<Category> getAll() {
		List<Category> categories = new ArrayList<Category>();
		
		categories = ofy.query(Category.class).order("parents").order("id").list();
		
		if (categories == null) {
			categories = new ArrayList<Category>();
		}
		
		return categories;
	}
	
}
